package com.liukai.personalbills.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

public class HttpUtil {
    public static String parseInfo(InputStream inputStream){
        BufferedReader reader = null;
        String line = "";
        StringBuilder response = new StringBuilder();

        try {
            reader = new BufferedReader(new InputStreamReader(inputStream));
            while((line = reader.readLine()) != null){
                response.append(line);
            }
            return response.toString();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                try{
                    reader.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public static String Intentweb(String myurl){
        HttpURLConnection connection = null;
        InputStream in = null;
        String str="";
        try{
         //   String path = URL2 + myurl;
            try {
                URL url = new URL(myurl);
                connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(30000);//建立连接超时
                connection.setReadTimeout(8000);//传递数据超时
                if (connection.getResponseCode()==200) {
                    in = connection.getInputStream();
                    str = parseInfo(in);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("url",myurl);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //意外退出时，连接关闭保护
            if(connection != null){
                connection.disconnect();
            }
            if(in != null){
                try{
                    in.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return str;
    }

    public static String sendPost(String path,String data) {
        String result = "";
        HttpURLConnection con = null;

        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;

        try {
            //设置路径
//            String path="http://192.168.1.111:8080/MyWebsite/androidregister.do";
            //?id="+username+"&password=" + pwd1+ "&email=" +email+"
            //创建URL对象
            URL url=new URL(path);
            //创建一个HttpURLconnection对象
            HttpURLConnection conn =(HttpURLConnection) url.openConnection();
            //设置请求方法
            conn.setRequestMethod("POST");
            //设置请求超时时间
            conn.setReadTimeout(5000);
            //conn.setConnectTimeout(5000);
            //Post方式不能设置缓存，需要手动设置
            //conn.setUseCaches(false);
            //准备要发送的数据
//            String data ="id="+URLEncoder.encode(username,"utf-8")+"&password="+URLEncoder.encode(pwd1,"utf-8")+"&email="+URLEncoder.encode(email,"utf-8");
            //String data ="id="+ username +"&password="+ pwd1 +"&email="+ email+"";
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//使用的是表单请求类型
            conn.setRequestProperty("Content-Length", data.length()+"");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //连接
            // conn.connect();
            //获得返回的状态码
            conn.getOutputStream().write(data.getBytes());
            int responseCode=conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = conn.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                result = URLDecoder.decode(resultBuffer.toString(),"UTF-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static String sendRequest(String urlParam,String requestType) {

        HttpURLConnection con = null;

        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;

        try {
            URL url = new URL(urlParam);
            //得到连接对象
            con = (HttpURLConnection) url.openConnection();
            //设置请求类型
            con.setRequestMethod(requestType);
            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应码
            int responseCode = con.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                String result = URLDecoder.decode(resultBuffer.toString(),"UTF-8");
                return result;
            }

        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
